package com.sz.netty.consumer;

import com.sz.netty.entity.DtuFtpMessageDetail;
import com.sz.netty.entity.DtuFtpInfo;
import com.sz.netty.service.DtuFtpMessageDetailService;
import com.sz.netty.service.DtuFtpInfoService;
import com.sz.netty.transport.TransportAnalyzer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Consumer for processing DTU record messages from RabbitMQ
 */
@Slf4j
@Component
public class DtuRecordConsumer {
    
    @Autowired
    private DtuFtpMessageDetailService dtuFtpMessageDetailService;
    
    @Autowired
    private DtuFtpInfoService dtuFtpInfoService;
    
    @Autowired
    private TransportAnalyzer transportAnalyzer;
    
    /**
     * Listen to DTU record queue and process new records
     * @param recordId the ID of the saved record
     */
    @RabbitListener(queues = "dtu.record.queue")
    public void processDtuRecord(Long recordId) {
        try {
            log.info("Received record ID from RabbitMQ: {}", recordId);
            
            // Get the record from database
            DtuFtpMessageDetail messageDetail = dtuFtpMessageDetailService.getById(recordId);
            if (messageDetail == null) {
                log.warn("Record not found for ID: {}", recordId);
                return;
            }
            
            // Get device info
            // We need to get the device ID from the associated message log
            // For now, we'll use the transport analyzer that's already implemented
            transportAnalyzer.processMessageDetailNonStatic(messageDetail);
            
        } catch (Exception e) {
            log.error("Error processing record ID {}: {}", recordId, e.getMessage(), e);
        }
    }
}